package com.huyn.baseframework.share;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.AsyncTask;
import android.os.Environment;
import android.view.View;

import com.huyn.baseframework.utils.BitmapUtils;
import com.huyn.baseframework.utils.Constant;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.UmengUtils;
import com.huyn.baseframework.utils.Utils;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXImageObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXMusicObject;
import com.tencent.mm.sdk.modelmsg.WXVideoObject;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ShareUtil {

	private static Context baseContext;

	private static IWXAPI wxApi = null;

	private static ShareUtil instance;
	private static ShareUtil getInstance() {
		if(instance == null)
			instance = new ShareUtil();
		return instance;
	}

	private ShareUtil() {
	}

	public static void initContext(Context ctx) {
		baseContext = ctx;
	}

	public static void startShare(Context context, ShareModule content) {
		try {
			if (content == null) {
				Utils.showToast(context, "分享数据有误");
				return;
			}

			if(baseContext == null)
				baseContext = context;

			if (content.mShareChannel != ShareType.TIMELINE && content.mShareChannel != ShareType.WECHAT) {
				if(content.mShareChannel == ShareType.WEIBO) {
					WeiboUtil.getInstance((Activity) context).startShare(context, content);
				} else {
					Utils.showToast(context, "无效类型");
				}
			} else {
				shareViaWechat(content);

				reportToUmeng(context, content);
			}
		} catch (RuntimeException e) {
			Utils.showToast(context, "分享失败");
		} catch (Exception e) {
			e.printStackTrace();
			Utils.showToast(context, "分享失败");
		}
	}

	private static void reportToUmeng(Context context, ShareModule module) {
		String id = module.mShareChannel != ShareType.TIMELINE ? UmengUtils.SHARE_VIA_WECHAT : UmengUtils.SHARE_VIA_TIMELINE;
		String value = "";
		switch (module.WeiXinTpye) {
			case ShareModule.TYPE_VIDEO:
				value = module.reportData;
				break;
			case ShareModule.TYPE_WEBPAGE:
				value = module.shareUrl;
				break;
			case ShareModule.TYPE_IMG:
				break;
			default:
				break;
		}
		UmengUtils.reportUmengEvent(context, id, value);
	}

	private static boolean shareViaWechat(ShareModule params) {
		wxApi = WXAPIFactory.createWXAPI(baseContext, Constant.APP_ID, false);
		wxApi.registerApp(Constant.APP_ID);
		if(wxApi.isWXAppInstalled()) {
			getInstance().new ShareByWxTask().execute(params);
			return true;
		} else {
			Utils.showToast(baseContext, "要先安装微信才能分享哦！");
			return false;
		}
	}

	public static boolean isWXAppInstalled() {
		wxApi = WXAPIFactory.createWXAPI(baseContext, Constant.APP_ID, false);
		return wxApi == null ? false : wxApi.isWXAppInstalled() ;
	}

	/**
	 * 微信分享注意事项：
	 * thumbimg大小不能超过32kb，title大小不能超过512Bytes，description大小不能超过1KB
	 * @author user
	 */
	private class ShareByWxTask extends AsyncTask<ShareModule, Void, Integer> {

		public ShareByWxTask() {
		}

		protected void onPreExecute() {
		}

		@Override
		protected Integer doInBackground(ShareModule... params) {
			try {
				if(params == null || params.length == 0)
					return -1;
				ShareModule para = params[0];
				Utils.sysout("imgPath:::::" + para.imagePath);
				if(para.mShareChannel == ShareType.WECHAT) {
					if (para.WeiXinTpye == ShareModule.TYPE_WEBPAGE) {
						WXWebpageObject webpage = new WXWebpageObject();
						webpage.webpageUrl = para.shareUrl;
						WXMediaMessage msg = new WXMediaMessage(webpage);
						if(para.title.length() < 100)
							msg.title = para.title;
						else
							msg.title = para.title.substring(0, 100);
						if(StringUtils.isNotBlank(para.content)) {
							if(para.content.length() < 200)
								msg.description = para.content;
							else
								msg.description = para.content.substring(0, 200);
						}
						Bitmap thumb = parsePic(para.imgBm);
						msg.setThumbImage(thumb);

						SendMessageToWX.Req req = new SendMessageToWX.Req();
						req.transaction = buildTransaction("webpage");
						req.message = msg;
						req.scene = SendMessageToWX.Req.WXSceneSession;//分享到好友
						wxApi.sendReq(req);
					}else if (para.WeiXinTpye == ShareModule.TYPE_IMG) {
						if (para.imgBm != null || StringUtils.isNotBlank(para.imagePath)) {
							WXImageObject wxImg = new WXImageObject();
							if(StringUtils.isNotBlank(para.imagePath))
								wxImg.imagePath = para.imagePath;
							else
								wxImg = new WXImageObject(para.imgBm);
							WXMediaMessage msg = new WXMediaMessage(wxImg);

							SendMessageToWX.Req req = new SendMessageToWX.Req();
							req.transaction = buildTransaction("img");
							req.message = msg;
							req.scene = SendMessageToWX.Req.WXSceneSession;//分享到好友
							wxApi.sendReq(req);
						}else{
							Utils.showToast(baseContext, "请等待图片加载完毕");
						}
					} else if (para.WeiXinTpye == ShareModule.TYPE_VIDEO) {
						if (para.imgBm != null || StringUtils.isNotBlank(para.imagePath)) {
							WXVideoObject wxVedio = new WXVideoObject();
							wxVedio.videoUrl = para.shareUrl;
							WXMediaMessage msg = new WXMediaMessage(wxVedio);
							msg.title = para.title;
							msg.description = para.content;
							Bitmap thumb;
							if (StringUtils.isNotBlank(para.imagePath)) {
								thumb = parsePic(para.imagePath);
							} else {
								thumb = parsePic(para.imgBm);
							}
							msg.setThumbImage(thumb);
							SendMessageToWX.Req req = new SendMessageToWX.Req();
							req.transaction = buildTransaction("video");
							req.message = msg;
							req.scene = SendMessageToWX.Req.WXSceneSession;//分享到好友
							wxApi.sendReq(req);
						}else{
							Utils.showToast(baseContext, "请等待图片加载完毕");
						}
					} else if (para.WeiXinTpye == ShareModule.TYPE_MUSIC) {
						if (para.imgBm != null || StringUtils.isNotBlank(para.imagePath)) {
							WXMusicObject wxMusic = new WXMusicObject();
							wxMusic.musicUrl = para.shareUrl;
							wxMusic.musicDataUrl = para.musicDataUrl;
							WXMediaMessage msg = new WXMediaMessage(wxMusic);
							msg.title = para.title;
							msg.description = para.content;
							Bitmap thumb;
							if (StringUtils.isNotBlank(para.imagePath)) {
								thumb = parsePic(para.imagePath);
							} else {
								thumb = parsePic(para.imgBm);
							}
							msg.setThumbImage(thumb);
							SendMessageToWX.Req req = new SendMessageToWX.Req();
							req.transaction = buildTransaction("music");
							req.message = msg;
							req.scene = SendMessageToWX.Req.WXSceneSession;//分享到好友
							wxApi.sendReq(req);
						}else{
							Utils.showToast(baseContext, "请等待图片加载完毕");
						}
					}
				} else if(para.mShareChannel == ShareType.TIMELINE) {
					if (para.WeiXinTpye == ShareModule.TYPE_WEBPAGE) {
						WXWebpageObject webpage = new WXWebpageObject();
						webpage.webpageUrl = para.shareUrl;
						WXMediaMessage msg = new WXMediaMessage(webpage);
						if(para.title.length() < 100)
							msg.title = para.title;
						else
							msg.title = para.title.substring(0, 100);
						if(StringUtils.isNotBlank(para.content)) {
							if(para.content.length() < 200)
								msg.description = para.content;
							else
								msg.description = para.content.substring(0, 200);
						}
						Bitmap thumb = parsePic(para.imgBm);
						msg.setThumbImage(thumb);

						SendMessageToWX.Req req = new SendMessageToWX.Req();
						req.transaction = buildTransaction("webpage");
						req.message = msg;
						req.scene = SendMessageToWX.Req.WXSceneTimeline;//分享到朋友圈
						wxApi.sendReq(req);
					}else if (para.WeiXinTpye == ShareModule.TYPE_IMG) {
						if (para.imgBm != null || StringUtils.isNotBlank(para.imagePath)) {
							WXImageObject wxImg = new WXImageObject();
							if(StringUtils.isNotBlank(para.imagePath))
								wxImg.imagePath = para.imagePath;
							else
								wxImg = new WXImageObject(para.imgBm);
							WXMediaMessage msg = new WXMediaMessage(wxImg);
//							Bitmap thumb = parsePic(para.imageData);
//							if(thumb == null) {
//								thumb = BitmapFactory.decodeResource(baseContext.getResources(), R.drawable.icon_rect);
//							}
//							msg.setThumbImage(thumb);
							SendMessageToWX.Req req = new SendMessageToWX.Req();
							req.transaction = buildTransaction("img");
							req.message = msg;
							req.scene = SendMessageToWX.Req.WXSceneTimeline;//分享到朋友圈
							wxApi.sendReq(req);
						}else{
							Utils.showToast(baseContext, "请等待图片加载完毕");
						}
					}else if (para.WeiXinTpye == ShareModule.TYPE_VIDEO) {
						if (para.imgBm != null || StringUtils.isNotBlank(para.imagePath)) {
							WXVideoObject wxVedio = new WXVideoObject();
							wxVedio.videoUrl = para.shareUrl;
							WXMediaMessage msg = new WXMediaMessage(wxVedio);
//						webpage.webpageUrl = para.url;
//						WXMediaMessage msg = new WXMediaMessage(webpage);
							if (para.title.length() < 100)
								msg.title = para.title;
							else
								msg.title = para.title.substring(0, 100);
							if (StringUtils.isNotBlank(para.content)) {
								if (para.content.length() < 200)
									msg.description = para.content;
								else
									msg.description = para.content.substring(0, 200);
							}
							Bitmap thumb;
							if (StringUtils.isNotBlank(para.imagePath)) {
								thumb = parsePic(para.imagePath);
							} else {
								thumb = parsePic(para.imgBm);
							}
							msg.setThumbImage(thumb);
							SendMessageToWX.Req req = new SendMessageToWX.Req();
							req.transaction = buildTransaction("video");
							req.message = msg;
							req.scene = SendMessageToWX.Req.WXSceneTimeline;//分享到朋友圈
							wxApi.sendReq(req);
						}else{
							Utils.showToast(baseContext, "请等待图片加载完毕");
						}
					} else if (para.WeiXinTpye == ShareModule.TYPE_MUSIC) {
						if (para.imgBm != null || StringUtils.isNotBlank(para.imagePath)) {
							WXMusicObject wxMusic = new WXMusicObject();
							wxMusic.musicUrl = para.shareUrl;
							wxMusic.musicDataUrl = para.musicDataUrl;
							WXMediaMessage msg = new WXMediaMessage(wxMusic);
							msg.title = para.title;
							msg.description = para.content;
							Bitmap thumb;
							if (StringUtils.isNotBlank(para.imagePath)) {
								thumb = parsePic(para.imagePath);
							} else {
								thumb = parsePic(para.imgBm);
							}
							msg.setThumbImage(thumb);
							SendMessageToWX.Req req = new SendMessageToWX.Req();
							req.transaction = buildTransaction("music");
							req.message = msg;
							req.scene = SendMessageToWX.Req.WXSceneTimeline;//分享到朋友圈
							wxApi.sendReq(req);
						}else{
							Utils.showToast(baseContext, "请等待图片加载完毕");
						}
					}
				} else {
					return -1;
				}
			} catch(Exception e) {
				e.printStackTrace();
				return -1;
			}
			return 0;
		}

		protected void onPostExecute(Integer result) {
			if(result != 0) {
				Utils.showToast(baseContext, "分享失败");
			}
		}

	}

	public static boolean isAppInstalled(Context context, String pkg) {
		PackageManager pm = context.getPackageManager();
		boolean installed =false;
		try {
			pm.getPackageInfo(pkg, PackageManager.GET_ACTIVITIES);
			installed =true;
		} catch(Exception e) {
			installed =false;
		}
		return installed;
	}

	private static Bitmap getPic(String path) {
		if(StringUtils.isEmpty(path)) {
			return null;
		}
		Bitmap bitmap = BitmapFactory.decodeFile(path);
		if(bitmap==null) {
			return null;
		}
		return compressImage(bitmap);
	}

	public static Bitmap parsePic(String path) {
		if(StringUtils.isEmpty(path)) {
			return null;
		}
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		Bitmap bitmap =  BitmapFactory.decodeFile(path, options);
		options.inSampleSize = BitmapUtils.calculateInSampleSizeStrict(options, 100, 100);//设置缩放比例
		options.inJustDecodeBounds = false;
		bitmap = BitmapFactory.decodeFile(path, options);
		if(bitmap==null)
		{
			return null;
		}
		return compressImage(bitmap);
	}

	public static Bitmap parsePic(Bitmap image) {
		try {
			if(image == null)
				return null;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
			if( baos.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出	
				baos.reset();//重置baos即清空baos
				image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%，把压缩后的数据存放到baos中
			}
			ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
			BitmapFactory.Options newOpts = new BitmapFactory.Options();
			//开始读入图片，此时把options.inJustDecodeBounds 设回true了
			newOpts.inJustDecodeBounds = true;
			Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
			newOpts.inJustDecodeBounds = false;
			newOpts.inSampleSize = BitmapUtils.calculateInSampleSizeStrict(newOpts, 200, 200);
			//重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
			isBm = new ByteArrayInputStream(baos.toByteArray());
			bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
			return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
		} catch(Exception e) {
			e.printStackTrace();
			return null;
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
			return null;
		}
	}

	public static byte[] parseBimap(Bitmap image) {
		try {
			if(image == null)
				return null;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
			if( baos.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出	
				baos.reset();//重置baos即清空baos
				image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%，把压缩后的数据存放到baos中
			}
			return baos.toByteArray();//压缩好比例大小后再进行质量压缩
		} catch(Exception e) {
			e.printStackTrace();
			return null;
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
			return null;
		}
	}
	public static Bitmap compressImage(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while ( baos.toByteArray().length / 1024>30) {	//循环判断如果压缩后图片是否大于30kb,大于继续压缩		
			baos.reset();//重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;//每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
		return bitmap;
	}

	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}

	public static String storeToFile(Bitmap bitmap) {
		FileOutputStream fOut = null;
		try {
			String src = Environment.getExternalStorageDirectory().getPath() + "/gewaratemp/tempshare" + System.currentTimeMillis() + ".jpg";
			File f = new File(src);
			if(!f.getParentFile().exists())
				f.getParentFile().mkdirs();
			f.createNewFile();
			fOut = new FileOutputStream(f);

			//不压缩和只压缩一点大小相差巨大！
			bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fOut);

			fOut.flush();
			return src;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if(fOut!=null) {
				try {
					fOut.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public static void clearCache() {
		try {
			String src = Environment.getExternalStorageDirectory().getPath() + "/gewaratemp/";
			File file = new File(src);
			if(file.exists()) {
				if (file.isFile()) {
					file.delete();
					return;
				}
				if(file.isDirectory()){
					File[] childFiles = file.listFiles();
					if (childFiles == null || childFiles.length == 0) {
//						file.delete();
						return;
					}
					for (int i = 0; i < childFiles.length; i++) {
						childFiles[i].delete();
					}
//					file.delete();
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	public static Bitmap compress(View view, int w, int h) {
		try {
			Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_4444);
			view.draw(new Canvas(bitmap));

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
//			int options = 80;
//			while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
//				baos.reset();// 重置baos即清空baos
//				options -= 10;// 每次都减少10
//				bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
//
//			}
			ByteArrayInputStream isBm = new ByteArrayInputStream(
					baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
			bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片

			Utils.Log("bitmap", "bitmap w:" + bitmap.getWidth() + " h:" + bitmap.getHeight() + "size:" + baos.toByteArray().length);
			return bitmap;
		} catch(OutOfMemoryError e) {
			e.printStackTrace();
			return null;
		}
	}

}
